package com.joe.learn.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 求数组中两个数和等于指定的数。并返回这两个数的坐标。
 */
public class TwoSum {

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[]{3, 2, 4}, 6)));
    }

    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        //查找数字是否存在可以再优化
        Map<Integer, Integer> temp = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int sub = target - nums[i];
            if (temp.containsKey(sub)) {
                return new int[]{temp.get(sub), i};
            }
            temp.put(nums[i], i);
        }
        return result;
    }
}
